package com.company.nuwa.common.key;

import cn.hutool.extra.spring.SpringUtil;
import com.google.common.base.Joiner;
import jakarta.validation.constraints.NotNull;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;

/**
 * <p>缓存key:改类提供以模块名命名的风格：applicationName:key</p>
 *
 * @author lili
 * @version 1.0: ApplicationNamedKeyGenerator.java
 * @date 2023/2/9 11:54
 */
public class ApplicationNamedKeyGenerator {

    private static final String KEY_SPLIT        = ":";

    private static final Joiner JOINER           = Joiner.on(KEY_SPLIT);

    private static final String GLOBAL_NAME      = "global";

    private static final String APPLICATION_NAME = StringUtils.upperCase(
        SpringUtil.getApplicationContext().getEnvironment().getProperty("spring.application.name"));

    /**
     * 拼凑key
     *
     * @param keys
     * @return
     */
    public static String genKey(@NonNull String... keys) {
        return genKey(false, keys);
    }

    /**
     * 拼凑key
     *
     * @param ignoreApplicationName 是否忽略applicationName，若忽略则用'global'代替
     * @param keys
     * @return
     */
    public static String genKey(boolean ignoreApplicationName, @NonNull String... keys) {
        String[] params = new String[keys.length + 1];
        params[0] = ignoreApplicationName ? GLOBAL_NAME : APPLICATION_NAME;
        System.arraycopy(keys, 0, params, 1, params.length - 1);
        return JOINER.join(params);
    }

    /**
     * 拼凑key
     *
     * @param keys
     * @return
     */
    public static String genNormalKey(@NotNull String... keys) {
        return JOINER.join(keys);
    }
}
